package com.at.c09_method_area;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 内存泄露测试
 * -Xms1m -Xmx1m -XX:+PrintGC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heap.bin
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/7/9 14:45
 */
public class MemoryLeak {
    private static List<Object> list = new ArrayList<>();

    public void add(Object object) {
        list.add(object);
    }

    public static void main(String[] args) throws InterruptedException {
        MemoryLeak memoryLeak = new MemoryLeak();
        for (int i = 0; i < 100000; i++) {
            memoryLeak.add(new Object());
        }

        Thread.sleep(1000000);
    }

    public static void main2(String[] args) {
        MemoryLeak memoryLeak = new MemoryLeak();
        while (true) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            memoryLeak.run();
        }
    }

    private void run() {
        // 不断创造非核心线程
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.submit(()->{
//                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
}
